package com.gitee.cui.springcloud.controller;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.gitee.cui.springcloud.entities.CommonResult;
import com.gitee.cui.springcloud.entities.Payment;
import com.gitee.cui.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

/**
 * Controller控制层
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2022-03-04 14:55
 **/
@RestController
@Slf4j
@RequestMapping(value = "/payment")
public class PaymentController {

	@Resource
	private PaymentService paymentService;

	@Value("${server.port}")
	private String serverPort;

	@Resource
	private DiscoveryClient discoveryClient;

	@PostMapping(value = "/create")
	public CommonResult<Integer> create(@RequestBody Payment payment) {
		int result = paymentService.create(payment);
		log.info("创建成功，返回结果：{}", result);

		if (result > 0) {
			return new CommonResult<>(200, "创建成功，serverPort: " + serverPort, result);
		} else {
			return new CommonResult<>(444, "创建失败");
		}
	}

	@GetMapping(value = "/get/{id}")
	public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
		Payment payment = paymentService.getPaymentById(id);
		log.info("根据id：{}，查询结果为：{}", id , payment);
		if (payment != null) {
			return new CommonResult<>(200, "查询成功，serverPort: " + serverPort, payment);
		} else {
			return new CommonResult<>(444, "查询失败");
		}
	}

	@GetMapping(value = "/discovery")
	public Object discoveryClient() {
		List<String> services = discoveryClient.getServices();
		for (String service : services) {
			log.info("service: {}", service);
		}
		List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
		for (ServiceInstance instance : instances) {
			log.info("instance: serviceId: {}, Host: {}, Port: {}, URI: {}", instance.getServiceId(), instance.getHost(), instance.getPort(), instance.getUri());
		}
		return discoveryClient;
	}

	@GetMapping(value = "/get/lb")
	public String getLB() {
		return serverPort;
	}

	@GetMapping(value = "/feign/timeout")
	public String feignTimeout() {
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return serverPort;
	}

	@GetMapping(value = "/zikpin")
	public String zipkin() {
		return "I'm payment zipkin";
	}
}
